<template>
  <zeda-dialog
    v-model="visible"
    :title="(id <= 0 ? '新增' : '编辑') + ''"
    width="500px"
    :before-close="handleClose"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <form-button
      slot="footer"
      :loading="loading"
      @cancel="handleClose"
      @submit="submit"
    >
    </form-button>
  </zeda-dialog>
</template>
  
  <script>
import { detail, add, edit } from "@/api/configuration/energyUnitPrice.js";
import { replaceDigit, dealElectricity, replaceInteger } from "@/utils/index";
import CascaderSelect from "@/components/Select/CascaderSelect";
import FormButton from "@/components/FormButton";

export default {
  components: {
    FormButton,
    CascaderSelect,
  },
  props: {
    id: {
      type: [Number, String],
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false, // 按钮加载中判断
      areaProps: {
        value: "areaId",
        children: "children",
        label: "name",
        checkStrictly: false,
        expandTrigger: "hover",
      },
      apsForm: {
        formRef: "form",
        formData: {},
        labelWidth: "auto",
        formConfig: {
          formAttr: {
            // inline: true,
            "label-position": "right",
            size: "small",
            bsColumn: {
              col: 1,
              middle: true,
            },
            rules: {
              deptId: [
                {
                  required: true,
                  message: "请选择适用区域",
                  trigger: ["change", "blur"],
                },
              ],
              date: [
                {
                  required: true,
                  message: "请选择适用周期",
                  trigger: ["change", "blur"],
                },
              ],
              electricityConsumptionUnitPrice: [
                {
                  required: true,
                  message: "请输入电消费量",
                  trigger: "blur",
                },
              ],
              waterConsumptionUnitPrice: [
                {
                  required: true,
                  message: "请输入水消费量",
                  trigger: "blur",
                },
              ],
              coalConsumptionUnitPrice: [
                {
                  required: true,
                  message: "请输入煤炭消费量",
                  trigger: "blur",
                },
              ],
              naturalGasConsumptionUnitPrice: [
                {
                  required: true,
                  message: "请输入天燃气消费量",
                  trigger: "blur",
                },
              ],
              renewableEnergyConsumptionUnitPrice: [
                {
                  required: true,
                  message: "请输入再生能源消费量",
                  trigger: "blur",
                },
              ],
              greenElectricityConsumptionUnitPrice: [
                {
                  required: true,
                  message: "请输入绿电消费量",
                  trigger: "blur",
                },
              ],
              carbonOffsetConsumptionUnitPrice: [
                {
                  required: true,
                  message: "请输入碳汇消费量",
                  trigger: "blur",
                },
              ],
              gasolineConsumptionUnitPrice: [
                {
                  required: true,
                  message: "请输入汽油消费量",
                  trigger: "blur",
                },
              ],
              vehicleDieselFuelUnitPrice: [
                {
                  required: true,
                  message: "请输入柴油消费量",
                  trigger: "blur",
                },
              ],
              liquefiedPetroleumGasConsumptionUnitPrice: [
                {
                  required: true,
                  message: "请输入液化石油消费量",
                  trigger: "blur",
                },
              ],
              heatConsumptionUnitPrice: [
                {
                  required: true,
                  message: "请输入热力消费量",
                  trigger: "blur",
                },
              ],
              otherEnergyUnitPrice: [
                {
                  required: true,
                  message: "请输入其他能源消费量",
                  trigger: "blur",
                },
              ],
            },
          },
          properties: {
            //这里是渲染查询表单的表头和类型的数据
            deptId: {
              label: "适用区域",
              render: (h) => {
                let that = this;
                let valNum = that.$refs?.form?.getFieldsValue().deptId;
                let a = (
                  <CascaderSelect
                    values={valNum}
                    value={valNum}
                    requestMethod={"get"}
                    varient={"areaDept"}
                    size={"small"}
                    placeholder={"请选择区域"}
                    maxlength={12}
                    onInput={(value) => {
                      if (value && value.length > 0) {
                        this.$refs?.form?.setFieldValue(
                          "deptId",
                          value[value.length - 1]
                        );
                      }
                    }}
                  ></CascaderSelect>
                );
                return <div>{a}</div>;
              },
            },
            date: {
              label: "适用周期",
              typeName: "el-datePicker",
              type: "monthrange",
              "start-placeholder": "开始日期",
              "end-placeholder": "结束日期",
              "value-format": "yyyy-MM-dd HH:mm:ss",
            },
            electricityConsumptionUnitPrice: {
              label: "电消费量",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入电消费量"
                      value={
                        this.$refs?.form?.getFieldsValue()
                          .electricityConsumptionUnitPrice
                      }
                      clearable
                      maxlength={12}
                      onInput={(value) =>
                        this.setVal(value, "electricityConsumptionUnitPrice")
                      }
                    >
                      <template slot="append">元/千瓦时</template>
                    </el-input>
                  </div>
                );
              },
            },
            waterConsumptionUnitPrice: {
              label: "水消费量",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入水消费量"
                      value={
                        this.$refs?.form?.getFieldsValue()
                          .waterConsumptionUnitPrice
                      }
                      clearable
                      maxlength={12}
                      onInput={(value) =>
                        this.setVal(value, "waterConsumptionUnitPrice")
                      }
                    >
                      <template slot="append">元/立方米</template>
                    </el-input>
                  </div>
                );
              },
            },
            coalConsumptionUnitPrice: {
              label: "煤炭消费量",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入煤炭消费量"
                      value={
                        this.$refs?.form?.getFieldsValue()
                          .coalConsumptionUnitPrice
                      }
                      clearable
                      maxlength={12}
                      onInput={(value) =>
                        this.setVal(value, "coalConsumptionUnitPrice")
                      }
                    >
                      <template slot="append">元/吨</template>
                    </el-input>
                  </div>
                );
              },
            },
            naturalGasConsumptionUnitPrice: {
              label: "天燃气消费量",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入天燃气消费量"
                      value={
                        this.$refs?.form?.getFieldsValue()
                          .naturalGasConsumptionUnitPrice
                      }
                      clearable
                      maxlength={12}
                      onInput={(value) =>
                        this.setVal(value, "naturalGasConsumptionUnitPrice")
                      }
                    >
                      <template slot="append">元/立方米</template>
                    </el-input>
                  </div>
                );
              },
            },
            renewableEnergyConsumptionUnitPrice: {
              label: "再生能源消费量",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入再生能源消费量"
                      value={
                        this.$refs?.form?.getFieldsValue()
                          .renewableEnergyConsumptionUnitPrice
                      }
                      clearable
                      maxlength={12}
                      onInput={(value) =>
                        this.setVal(
                          value,
                          "renewableEnergyConsumptionUnitPrice"
                        )
                      }
                    >
                      <template slot="append">元/千卡</template>
                    </el-input>
                  </div>
                );
              },
            },
            greenElectricityConsumptionUnitPrice: {
              label: "绿电消费量",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入绿电消费量"
                      value={
                        this.$refs?.form?.getFieldsValue()
                          .greenElectricityConsumptionUnitPrice
                      }
                      clearable
                      maxlength={12}
                      onInput={(value) =>
                        this.setVal(
                          value,
                          "greenElectricityConsumptionUnitPrice"
                        )
                      }
                    >
                      <template slot="append">元/千伏安月</template>
                    </el-input>
                  </div>
                );
              },
            },
            carbonOffsetConsumptionUnitPrice: {
              label: "碳汇消费量",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入碳汇消费量"
                      value={
                        this.$refs?.form?.getFieldsValue()
                          .carbonOffsetConsumptionUnitPrice
                      }
                      clearable
                      maxlength={12}
                      onInput={(value) =>
                        this.setVal(value, "carbonOffsetConsumptionUnitPrice")
                      }
                    >
                      <template slot="append">元/吨</template>
                    </el-input>
                  </div>
                );
              },
            },
            gasolineConsumptionUnitPrice: {
              label: "汽油消费量",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入汽油消费量"
                      value={
                        this.$refs?.form?.getFieldsValue()
                          .gasolineConsumptionUnitPrice
                      }
                      clearable
                      maxlength={12}
                      onInput={(value) =>
                        this.setVal(value, "gasolineConsumptionUnitPrice")
                      }
                    >
                      <template slot="append">元/升</template>
                    </el-input>
                  </div>
                );
              },
            },
            vehicleDieselFuelUnitPrice: {
              label: "柴油消费量",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入柴油消费量"
                      value={
                        this.$refs?.form?.getFieldsValue()
                          .vehicleDieselFuelUnitPrice
                      }
                      clearable
                      maxlength={12}
                      onInput={(value) =>
                        this.setVal(value, "vehicleDieselFuelUnitPrice")
                      }
                    >
                      <template slot="append">元/升</template>
                    </el-input>
                  </div>
                );
              },
            },
            liquefiedPetroleumGasConsumptionUnitPrice: {
              label: "液化石油消费量",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入液化石油消费量"
                      value={
                        this.$refs?.form?.getFieldsValue()
                          .liquefiedPetroleumGasConsumptionUnitPrice
                      }
                      clearable
                      maxlength={12}
                      onInput={(value) =>
                        this.setVal(
                          value,
                          "liquefiedPetroleumGasConsumptionUnitPrice"
                        )
                      }
                    >
                      <template slot="append">元/千克</template>
                    </el-input>
                  </div>
                );
              },
            },
            heatConsumptionUnitPrice: {
              label: "热力消费量",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入热力消费量"
                      value={
                        this.$refs?.form?.getFieldsValue()
                          .heatConsumptionUnitPrice
                      }
                      clearable
                      maxlength={12}
                      onInput={(value) =>
                        this.setVal(value, "heatConsumptionUnitPrice")
                      }
                    >
                      <template slot="append">元/吉焦</template>
                    </el-input>
                  </div>
                );
              },
            },
            otherEnergyUnitPrice: {
              label: "其他能源消费量",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入其他能源消费量"
                      value={
                        this.$refs?.form?.getFieldsValue().otherEnergyUnitPrice
                      }
                      clearable
                      maxlength={12}
                      onInput={(value) =>
                        this.setVal(value, "otherEnergyUnitPrice")
                      }
                    >
                      <template slot="append">元/吨标准煤</template>
                    </el-input>
                  </div>
                );
              },
            },
          },
        },
      },
    };
  },
  watch: {
    visible(value) {
      if (value) {
        if (String(this.id).length > 0) {
          this.getInfo();
        }
      }
    },
  },
  methods: {
    setVal(value, key) {
      if (Number(value) > 9999999) {
        this.$alert("输入单位过大,请重新填写", "提示", {
          confirmButtonText: "确定",
          callback: (action) => {
            this.$refs?.form?.setFieldValue(key, "");
          },
        });
        return false;
      }
      this.$refs?.form?.setFieldValue(key, replaceDigit(value, 4));
    },
    getInfo() {
      detail(this.id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let newData = res?.data || {};
          newData.date = [newData.effectiveTime, newData.expirationTime];
          this.$refs?.form?.setFieldsValue(newData);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!错误码306004");
        });
    },
    submit() {
      const { date, ...other } = this.$refs?.form?.getFieldsValue();
      const [effectiveTime, expirationTime] = date || [];
      const data = {
        ...other,
        effectiveTime,
        expirationTime,
      };
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.id) {
            this.editRequest(data);
          } else {
            this.addRequest(data);
          }
        } else {
          return false;
        }
      });
    },
    addRequest(data) {
      add(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!错误码306002");
        });
    },
    editRequest(data) {
      let info = {
        id: this.id,
        ...data,
      };
      edit(info)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!错误码306003");
        });
    },
    handleClose(status) {
      this.$refs["form"].resetFields();
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
  },
};
</script>
  
  <style scoped lang="scss">
::v-deep .el-form {
  .el-input,
  .el-cascader,
  .el-input-number,
  .el-select {
    width: 100% !important;
  }
  .map {
    display: flex;
    .el-input {
      margin-right: 10px;
    }
  }
}

::v-deep .el-dialog__footer {
  padding-top: 0px;
}
</style>
  